//
//  MYLoadViewController.swift
//  NewMicroblog
//
//  Created by apple on 2016/10/23.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD

class MYLoadViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
       setupUI()
       setNav()
    }
    
    private func setupUI(){
        
    }
    
    /// 取消按钮点
    @objc private func cancel(){
        dismiss(animated: true, completion: nil)
    }
    /// 自动填充按钮点击
    @objc private func autoAdd(){
        // jsString
        let jsString = "document.getElementById('userId').value='\(MYWBNAME)',document.getElementById('passwd').value='\(MYWBPASSWD)'"
        // js注入
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    private func setNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: nil, title: "取消", target: self, action: #selector(cancel))
         navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: nil, title: "自动填充", target: self, action: #selector(autoAdd))
    }
    
    lazy var webView: UIWebView = {
         let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(MYAPPKEY)&redirect_uri=\(MYREDIRECTURI)")!
        let request = URLRequest(url: url)
        let webView = UIWebView()
        webView.delegate = self
        webView.loadRequest(request)
        return webView
     }()
    
}
extension MYLoadViewController : UIWebViewDelegate{
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let string = request.url?.absoluteString
        if let u = string, u.hasPrefix(MYREDIRECTURI)  {
           let query = request.url?.query
            if let q = query {
                let code = q.substring(from: "code=".endIndex)
                print(code)
               MYUserinfoViewModel.sharedModel.getMessage(code: code, finish: { (isSuccess) in
                    if !isSuccess{
                    print("请求失败")
                    return
                }
                SVProgressHUD.show()
                print("请求成功")
                self.dismiss(animated: true, completion: { 
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: MYROOTCONTROLLERVC), object: nil)
                })
               })
                
                return false
            }
        }
        
        
        return true;
    
    }
    
    
}
